package top.retain;

/**
 * @author ivorfan
 * @date 2021/7/29 14:24
 */
public class SqrtTest {

    public static void main(String[] args) {
        SqrtTest sqrtTest = new SqrtTest();
        System.out.println(sqrtTest.sqrt(9, 0.000001));
    }
    public double sqrt(double target, double m) {
        double left = 1;
        double right = target;
        // newMid记录上一次的mid，和mid二分后进行对比误差
        double newMid;
        // 防止溢出
        double mid = left +(right - left) / 2;
        do {
            // 没有使用mid * mid防止溢出
            if (mid < target / mid) {
                left = mid;
            }else {
              right = mid;
            }
            newMid = mid;
            mid = left +(right - left) / 2;
        }while (left < right && abs(mid,newMid) > m);
        return mid;
    }

    public double abs(double a, double b) {
        return a > b ? a - b : b - a;
    }

}
